#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define MAXSIZE 512

char name[MAXSIZE];

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

// 从屏幕中读取数据并向服务器写
void *write_routine(void *arg) {
    int sockfd = *(int *)arg;
    while (1) {
        char buf[MAXSIZE], msg[MAXSIZE * 2 + 10] = {0};
        fgets(buf, MAXSIZE, stdin);
        if (strcmp(buf, "q\n") == 0) 
            break;
        sprintf(msg, "[%s] %s", name, buf);
    //    printf("msg = %s\n", msg);
        write(sockfd, msg, strlen(msg) - 1);
    }
    close(sockfd);
    // 这里为了保证另一个线程能够正常退出
    exit(0);
    return NULL;
}

// 从服务端返回信息并显示在屏幕上
void *read_routine(void *arg) {
    int sockfd = *(int *)arg;
    char buf[MAXSIZE];
    while (1) {
        int len = read(sockfd, buf, MAXSIZE);
        buf[len] = 0;
        if (len == -1)
            break;
        printf("%s\n", buf);
    }
    return NULL;
}

int main(int argc, char *argv[]) {
    int client_sock;
    if (argc != 4) {
        printf("Usage : %s <IP> <port> <name>\n", argv[0]);
        exit(1);
    }
    memcpy(name, argv[3], sizeof(argv[3]));
    if ((client_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        error_handling("socket() error!");
    }
    
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));

    

    if (connect(client_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        error_handling("connect() error!");
    }

    pthread_t pid1, pid2;
    pthread_create(&pid1, NULL, write_routine, (void *)&client_sock);
    pthread_create(&pid2, NULL, read_routine, (void *)&client_sock);
    
    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);
  
    close(client_sock);
    return 0;
}